import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

/**
 * @author Shangru Li
 * the class is provide the window for user to choose a file to read in
 * or a address to save the file
 */
public class myChooser extends JFileChooser {
	    boolean opening =false; // to identify whether it is in reading mode or saving mode
            String neededType = "txt"; // the affix of the file desired
    	public myChooser(String path){ //Constructor
    	   super(path);
    	}
    	//override the approveSelection function
    	public void approveSelection(){ 
    		File file;
                boolean end_with_txt = false;
                int index = this.getSelectedFile().getPath().lastIndexOf('.');
                if (index > 0 & index < (this.getSelectedFile().getPath().length() - 1)) { //to catch the extension of the file
                    String extension = this.getSelectedFile().getPath().substring(index + 1).toLowerCase();
                    if (extension.equals(neededType)) { // if the extension of this file is the same as the extension that can pass
                        end_with_txt = true; // it is also acceptable
                    } else {
                        end_with_txt = false;
                    }
                }
                if (end_with_txt) {
                    file = new File(this.getSelectedFile().getPath());
                } else {
                    file = new File(this.getSelectedFile().getPath() + ".txt");
                }
                
    		if(opening==true){ // if the user want to open a file
    			if(file.exists()){ // if the file exist
        	    	super.approveSelection(); //invoke the parent function(read in the file)
        	    }
        	    else //if no such a file
        	    	JOptionPane.showMessageDialog(null, "no such a file, please select again");//indicate the user to select again
    			
    		}
    		else{ // if the user want to save a file
    			if(file.exists()){ // if the file exist, ask the user to confirm whether to replace
    				int copy=JOptionPane.showConfirmDialog(null,"The file has already exsited, replace?",
    						"save",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);
    				if(copy==JOptionPane.YES_OPTION)//if the user want to replace 
    					super.approveSelection();//save the file
    			}	
    			else // if not file with the same name exist
    				super.approveSelection(); // save the file
    			}
    		}
    	}